<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-28
 * Time: 17:53
 */

namespace app\api\service\product;

use app\api\model\CouponUser;
use app\api\model\Product;
use app\api\model\Product as ProductModel;
use app\api\model\ProductOrder;
use app\api\model\ProductOrder as ProductOrderModel;
use app\api\model\ProductOrderContent;
use app\api\model\StoreUser;
use app\api\model\Team as TeamModel;
use app\api\model\TeamUser as TeamUserModel;
use app\api\model\TeamUser;
use app\api\model\User;
use app\api\model\User as UserModel;
use app\api\model\UserInvitation;
use app\api\service\coupon\CouponOrderSer;
use app\api\service\Token;
use app\api\validate\CheckRemark;
use app\lib\exception\ParameterException;
use think\Db;

class CreateOrderSer extends Token
{
    /**
     * 1.判断购物车信息
     * 2. 判断优惠券
     * 3.创建订单信息
     */
    // 用户信息
    private $user;

    // 前端传来的信息
    private $postArr;

    // 购物车信息
    private $product;

    // 订单价格
    private $actual_price;

    // 产品单价
    private $once_price;

    private $coupon_money;

    private $teamUser;

    private $teamUserId;

    function __construct($postArr)
    {
        (new CheckRemark())->goCheck();
        $this->user = User::get(self::getCurrentUid());
        $this->product = Product::get($postArr['product_id']);
        $this->postArr = $postArr;
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeData();
    }

    // 判断购物车信息
    private function judgeData()
    {
        if($this->user['status'] == 1) {
            throw new ParameterException([
                'msg' => [
                    'order' => '请先进行登录操作!'
                ]
            ]);
        }
        if($this->user['status'] == 2) {
            throw new ParameterException([
                'msg' => [
                    'order' => '请先进行获取手机号操作!'
                ]
            ]);
        }
        $this->judgeUserInvitation();
        $this->actual_price = $this->postArr['total'];
        $this->product = self::getProductPrice($this->product);
        $this->once_price = $this->product['price'];
        $price = $this->postArr['number'] * $this->once_price;
        if($this->product['product_type'] == 2) {
            if($this->postArr['coupon_id'] > 0) {
                throw new ParameterException([
                    'msg' => [
                        'order' => '专属卡不能使用优惠券!'
                    ]
                ]);
            }
        }
        if($this->postArr['coupon_id'] > 0) {
            $couponOrder = new CouponOrderSer($this->postArr['coupon_id'],$price);
            $this->coupon_money = $couponOrder->entrance();
            if(!$this->coupon_money) {
                $this->coupon_money = 0;
            }
            $price = $price - $this->coupon_money;
        }
        if($this->actual_price != $price) {
            throw new ParameterException([
                'msg' => [
                    'order' => '结算金额不同，请重新结算!'
                ]
            ]);
        }
        $this->checkProductType();
        $time = time();
        if($this->product['product_type'] == 1) {

            if($this->product['start_time'] > $time) {
                throw new ParameterException([
                    'msg' => [
                        'order' => '该产品还未开始售卖!'
                    ]
                ]);
            }
            if($time > $this->product['end_time']){
                throw new ParameterException([
                    'msg' => [
                        'order' => '该产品已停止售卖!'
                    ]
                ]);
            }
            if($this->product['max_num']) {
                if($this->postArr['number'] > $this->product['max_num']) {
                    throw new ParameterException([
                        'msg' => [
                            'order' => '该产品最多购买'.$this->product['max_num'].'!'
                        ]
                    ]);
                }
            }
        }
        return $this->createOrder();
    }
    
    // 判断上级信息
    private function judgeUserInvitation()
    {
        $userInvite = UserInvitation::where('invitee',$this->user['id'])->find();
        if($userInvite['type'] == 1) {
            $user = User::get($userInvite['inviter']);
            if(!$user){
                throw new ParameterException([
                    'msg' => [
                        'order' => '请从店员处注册后再下单购买'
                    ]
                ]);
            }
            if($this->product['store_id'] != $user['store_id']) {
                throw new ParameterException([
                    'msg' => [
                        'order' => '订单所属门店与您绑定门店不同'
                    ]
                ]);
            }
        }elseif($userInvite['type'] == 2){
            $user = StoreUser::get($userInvite['inviter']);
            if(!$user){
                throw new ParameterException([
                    'msg' => [
                        'order' => '请从店员处注册后再下单购买'
                    ]
                ]);
            }
            if($this->product['store_id'] != $user['store_id']) {
                throw new ParameterException([
                    'msg' => [
                        'order' => '订单所属门店与您绑定门店不同'
                    ]
                ]);
            }
        }elseif($userInvite['type'] == 3){
            $user = TeamUser::get($userInvite['inviter']);
            if(!$user){
                throw new ParameterException([
                    'msg' => [
                        'order' => '请从店员处注册后再下单购买'
                    ]
                ]);
            }
            if($this->product['store_id'] != $user['store_id']) {
                throw new ParameterException([
                    'msg' => [
                        'order' => '订单所属门店与您绑定门店不同'
                    ]
                ]);
            }
        }else {
            throw new ParameterException([
                'msg' => [
                    'order' => '请从店员处注册后再下单购买'
                ]
            ]);
        }
    }

    // 判断专属卡
    private function checkProductType()
    {
        if($this->postArr['team_user_id'] > 0) {
            $teamUserInfo = UserModel::where('id',$this->postArr['team_user_id'])->find();
            if($teamUserInfo['type'] == 5 || $teamUserInfo['type'] == 6) {
                $this->teamUser = TeamUserModel::where('user_id',$teamUserInfo['id'])->find();
                $this->teamUserId = $this->teamUser['id'];
                $productOrder = ProductOrderModel::where('order_type','eq',2)
                    ->where('order_team_user_id','eq',$this->teamUser['id'])
                    ->where('status','gt',1)
                    ->find();
                if($productOrder) {
                    throw new ParameterException([
                        'msg' => [
                            'product' => '该专属卡已经被购买'
                        ]
                    ]);
                }
                $team = TeamModel::where('id',$this->teamUser['team_id'])->find();
                $product = ProductModel::where('id',$team['product_id'])->find();
                if(!$product) {
                    throw new ParameterException([
                        'msg' => [
                            'product' => '专属卡为空'
                        ]
                    ]);
                }
                if($product['id'] != $this->product['id']) {
                    throw new ParameterException([
                        'msg' => [
                            'product' => '专属卡信息错误'
                        ]
                    ]);
                }
                if($this->postArr['number'] > 1) {
                    throw new ParameterException([
                        'msg' => [
                            'product' => '专属卡只允许购买一张'
                        ]
                    ]);
                }
            }
        }
    }

    // 创建订单信息
    private function createOrder()
    {

        // 创建订单
        Db::startTrans();
        try{
            $mode = ProductOrder::create([
                'user_id' => $this->user['id'],
                'price' => $this->actual_price,
                'actual_price' => $this->actual_price,
                'order_no' => self::makeOrderNo(),
                'remark' => $this->postArr['remark'],
                'store_id' => $this->product['store_id'],
                'coupon_id' => $this->postArr['coupon_id'],
                'coupon_money' => $this->coupon_money,
                'order_type' => $this->product['product_type'],
                'order_team_user_id' => $this->teamUserId,
            ]);
            $out_trade_no = '1shu2020'.$mode->id;
            $mode->out_trade_no = $out_trade_no;
            $mode->save();
            if($this->product['product_type'] == 2) {
                $this->product['start_time'] = time();
                $this->product['end_time'] = time()+ ($this->product['end_time']*86400);
            }
            ProductOrderContent::create([
                'product_id' => $this->product['id'],
                'img_id' => $this->product['img_id'],
                'product_number' => $this->postArr['number'],
                'product_name' => $this->product['name'],
                'product_price' => $this->once_price,
                'product_order_id' => $mode->id,
                'user_id' => $this->user['id']
            ]);
            if($this->postArr['coupon_id'] > 0){
                CouponUser::where('id',$this->postArr['coupon_id'])->setDec('surplus_times');
            }
            Db::commit();
            return writeJson(201, [ 'out_trade_no'=>$out_trade_no], '订单生成成功！');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }
}